package com.xinting.piano.service;

import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.xinting.piano.app.PRoutineService;
import com.xinting.piano.data.PApp;
import com.xinting.piano.data.PMessage;
import com.xinting.piano.data.PUser;
import com.xinting.piano.lib.network.PNetWork;
import com.xinting.piano.lib.util.PUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wuxinting on 15/11/14.
 * 私信业务
 */
public class PMessageService {

    public static final String LOG_TAG = PMessage.LOG_TAG+"service";

    public static final long ROUTINE_PERIOD = 15 * 60 * 1000; //15 mins

    //私信远程地址
    public static final String URL_MESSAGE = "account/message";
    public static final String URL_SEND_MESSAGE = "account/add_message";

    public static final String KEY_TO_USER = "to";
    public static final String KEY_FROM_USER = "from";

    /**
     * 拉取信件
     * @return
     */
    public boolean pullMessage() {
//        MessageRoutineTask task = new MessageRoutineTask(-1);
//        Message msg = Message.obtain(null, PRoutineService.MSG_ADD_ROUTINE_TASK);
//        msg.obj = task;
//        try {
//            service.send(msg);
//        } catch (RemoteException e) {
//            Log.e(LOG_TAG, e.getMessage());
//            return false;
//        }
        return true;
    }

    /**
     * 发送信件
     * @param to 接收人
     * @param content 内容
     * @return
     */
    public boolean sendMessage(PUser to, String content, IHandleJson handleJson) {
        Map<String, String> params = new HashMap<>();
        params.put(PApp.KEY_CONTENT, content);

        PUser me = PAccount.getInstance().getCurrentUser();
        params.put(KEY_FROM_USER, me.getId());
        params.put(KEY_TO_USER, to.getId());

        String url = PUtil.joinURL(PApp.URL_SERVER, URL_SEND_MESSAGE);
        try {
            PNetWork.getInstance().post(url, params, new HandleMessageHttpResult(handleJson));
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
            return false;
        }

        return true;
    }

    /**
     * 添加日常任务
     * @param messenger 后台service进程通信接口
     */
    public void addRoutine(Messenger messenger) {
        MessageRoutineTask task = new MessageRoutineTask();
        Message msg = Message.obtain(null, PRoutineService.MSG_ADD_ROUTINE_TASK);
        msg.obj = task;
        try {
            messenger.send(msg);
        } catch (RemoteException e) {
            Log.e(LOG_TAG, e.getMessage());
        }
    }

    /**
     * 处理message返回的消息
     */
    private class HandleMessageHttpResult implements PNetWork.IHandleHttpResult {

        private IHandleJson handleJson;
        public HandleMessageHttpResult(IHandleJson handleJson) {
            this.handleJson = handleJson;
        }

        @Override
        public void onRequest(Request req, IOException e) {

        }

        @Override
        public void onResponse(Response res) throws IOException {
            String rs = res.body().string();
            if (handleJson != null) {
                try {
                    handleJson.handleJson(new JSONObject(rs));
                } catch (JSONException e) {
                    Log.e(LOG_TAG, e.getMessage());
                }
            }
        }
    }

    /**
     * 查看私信的任务
     */
    public class MessageRoutineTask implements PRoutineService.IRoutineTask {

        private long period = ROUTINE_PERIOD;

        public MessageRoutineTask() {}
        public MessageRoutineTask(long period) {
            this.period = period;
        }

        @Override
        public int getId() {
            return PApp.ROUTINE_MESSAGE;
        }

        @Override
        public long getDelay() {
            return 0;
        }

        @Override
        public long getPeriod() {
            return period;
        }

        @Override
        public void setMessenger(Messenger messenger) {

        }

        @Override
        public void run() {
            Map<String, String> params = new HashMap<>();
            PAccount.getInstance().fillTokenToParam(params);

            try {
                Response response = PNetWork.getInstance().postSync(PUtil.joinURL(PApp.URL_SERVER, URL_MESSAGE), params);
                String res = response.body().string();
                Log.v(LOG_TAG, res);

                JSONObject json = new JSONObject(res);

                int code = json.getInt(PApp.ERR_CODE);
                if (code != PApp.ERR_SUCCESS) {
                    Log.w(LOG_TAG, json.getString(PApp.ERR_MSG));
                }

                if (json.has(PMessage.KEY_S)) {
                    Log.v(LOG_TAG, json.getString(PMessage.KEY_S));
                }
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage());
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage());
            }
        }
    }

}
